<template>
  <div>
    <div class="select-group">
      <div class="select-year" :style="{
        color: rec.showYearPicker ? '#3E77FA' : '#616366',
        width: props.fromType === 'home' ? '120px' : '167.5px',
      }" @click="() => handleSelectTime('year')">
        {{ rec.yearValue }}
        <span class="bottom-icon">{{ rec.showYearPicker ? "▲" : "▼" }} </span>
      </div>
      <div class="select-month" v-if="rec.baseConfig !== 'Week'" :style="{
        color: rec.showMonthPicker ? '#3E77FA' : '#616366',
        width: props.fromType === 'home' ? '120px' : '167.5px',
      }" @click="() => handleSelectTime('month')">
        {{ rec.monthValue }}
        <span class="bottom-icon">{{ rec.showMonthPicker ? "▲" : "▼" }}</span>
      </div>
      <div class="select-month" v-if="rec.baseConfig === 'Week'" :style="{
        color: rec.showSemesterPicker ? '#3E77FA' : '#616366',
        width: props.fromType === 'home' ? '120px' : '167.5px',
      }" @click="() => handleSelectTime('semester')">
        {{ rec.semesterValue }}
        <span class="bottom-icon">{{ rec.showSemesterPicker ? "▲" : "▼" }}</span>
      </div>
      <div class="select-month" v-if="props.fromType === 'home'" :style="{
        color: rec.showGradePicker ? '#3E77FA' : '#616366',
        width: props.fromType === 'home' ? '120px' : '167.5px',
      }" @click="() => handleSelectTime('grade')">
        {{ rec.gradeValue || "全部年级" }}
        <span class="bottom-icon">{{ rec.showGradePicker ? "▲" : "▼" }}</span>
      </div>

      <van-picker v-show="rec.showYearPicker" ref="yearRef" :columns="rec.yearColumns" :show-toolbar="false"
        @change="($event) => handleChange($event, 'year')" />

      <van-picker v-show="rec.showMonthPicker" ref="monthRef" :columns="rec.monthColumns" :show-toolbar="false"
        @change="($event) => handleChange($event, 'month')" />

      <van-picker v-show="rec.showSemesterPicker" ref="semesterRef" :columns="rec.semesterColumns" :show-toolbar="false"
        @change="($event) => handleChange($event, 'semester')" />

      <van-picker v-show="props.fromType === 'home' && rec.showGradePicker" ref="gradeRef" :columns="rec.gradeColumns"
        :show-toolbar="false" @change="($event) => handleChange($event, 'grade')" />
    </div>
    <div class="ylc-weekList" ref="scrollContainer" v-if="rec.baseConfig === 'Week'">
      <div v-for="item in rec.weekList" :key="item.weekIndex" class="ylc-weekList-item"
        :class="rec.weekValue === item.weekIndex ? 'action' : ''" @click="checkWeekValue(item)">
        第{{ item.weekIndex }}周
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import type { PickerInstance } from "vant";
import { nextTick, onMounted, reactive, ref } from "vue";
import LocalCache from "@/utils/cache";
import { getWeek } from "@/service/modules/public/public";
import dayjs from "dayjs";

const props = defineProps({
  fromType: String,
});

const yearRef = ref<PickerInstance>();
const monthRef = ref<PickerInstance>();
const gradeRef = ref<PickerInstance>();
const semesterRef = ref<PickerInstance>();
const scrollContainer = ref<HTMLDivElement>();

const rec = reactive({
  yearSemAddVacationList: [],
  weekList: [],
  gradeList: [],
  yearColumns: [],
  gradeColumns: [],
  semesterColumns: [],
  showYearPicker: false,
  showMonthPicker: false,
  showGradePicker: false,
  showSemesterPicker: false, // 学期
  semesterValue: "",
  yearValue: "",
  monthValue: "",
  gradeValue: "",
  weekValue: "",
  monthColumns: new Array(12).fill("").map((item, index) => index + 1 + "月"),
  baseConfig: "",
  findSemester: "",
  findGrage: "全部年级"
});

onMounted(async () => {
  // 年级列表
  const gradeList = LocalCache.getSession("gradeList");
  rec.gradeList = LocalCache.getSession("gradeList");
  rec.gradeColumns = ["全部年级", ...gradeList.map((item) => item.unitName)];

  // 学年选项列表
  const yearSemAddVacationList = LocalCache.getSession(
    "yearSemAddVacationList"
  );

  // 学年选项列表
  rec.yearSemAddVacationList = yearSemAddVacationList;
  rec.yearColumns = yearSemAddVacationList.map((item) => item.accYearName);
  nextTick(async () => {
    const defaultList: any = rec.yearSemAddVacationList.filter(
      (item: any) =>
        new Date(item.beginDay).getTime() <= new Date().getTime() &&
        new Date(item.endDay).getTime() >= new Date().getTime()
    );

    // 学年选项默认值
    yearRef.value?.setColumnValue(
      0,
      rec.yearColumns[rec.yearColumns.length - 1]
    );

    rec.yearValue = defaultList[0].accYearName;

    // 获取配置
    rec.baseConfig = LocalCache.getSession("baseConfig")?.value;

    // 学期
    if (rec.baseConfig === "Semester") {
      // 学期选项默认列表和值
      const currentSemester = await filterSemester(defaultList[0].accYearName);
      // 学期选项默认值
      rec.monthValue = currentSemester.slice(9);

      // 周期选项默认值
      monthRef.value?.setColumnValue(0, currentSemester);
    } else if (rec.baseConfig === "Week") {
      const currentSemester = await getWeekList();
      // 周期选项默认值
      rec.semesterValue = currentSemester;
      // 周期选项默认值
      semesterRef.value?.setColumnValue(0, currentSemester);
    } else {
      // 月份选项默认值
      rec.monthValue = rec.monthColumns[dayjs().month()];
      monthRef.value?.setColumnValue(0, rec.monthColumns[dayjs().month()]);
    }

    emit(
      "timeChange",
      convertTime({
        year: rec.yearValue,
        month: rec.monthValue,
        grade: "全部年级",
      })
    );
  });
});

// 选择教学周
const checkWeekValue = (item) => {
  rec.weekValue = item.weekIndex;
  emit(
    "timeChange",
    convertTime({
      year: rec.yearValue,
      month: rec.monthValue,
      grade: rec.findGrage,
    })
  );
};

const handleSelectTime = (type) => {
  if (type === "year") {
    rec.showYearPicker = !rec.showYearPicker;
    rec.showMonthPicker = false;
    rec.showSemesterPicker = false;
    rec.showGradePicker = false;
  } else if (type === "month") {
    rec.showMonthPicker = !rec.showMonthPicker;
    rec.showYearPicker = false;
    rec.showSemesterPicker = false;
    rec.showGradePicker = false;
  } else if (type === "semester") {
    rec.showSemesterPicker = !rec.showSemesterPicker;
    rec.showMonthPicker = false;
    rec.showYearPicker = false;
    rec.showGradePicker = false;
  } else {
    rec.showGradePicker = !rec.showGradePicker;
    rec.showSemesterPicker = false;
    rec.showYearPicker = false;
    rec.showMonthPicker = false;
  }
};

const handleChange = async (value, type) => {
  // console.log(value, "value");
  // console.log(type, "type");

  if (type === "year") {
    rec.yearValue = value;

    if (rec.baseConfig === "Semester") {
      filterSemester(value);
    } else if (rec.baseConfig === "Week") {
      await getWeekList();
    }
  }
  if (type === "semester") {
    rec.semesterValue = value;
    rec.findSemester = rec.yearSemAddVacationList
      .find((item) => item.accYearName === rec.yearValue)
      ?.semAddVacation.find((item2) => item2.name.slice(9) === value);
    await getWeek({
      beginDay: rec.findSemester?.beginDay,
      endDay: rec.findSemester?.endDay
    }).then((res) => {
      if (res.code === 0) {
        rec.weekList = res.rows;
        rec.weekValue = res.rows[0].weekIndex;
      }
    })
  }

  if (type === "month") {
    rec.monthValue = value;
  }

  if (type === "grade") {
    rec.gradeValue = value;
    // 年级选项默认值
    gradeRef.value?.setColumnValue(0, value);

    if (value === "全部年级") {
      rec.findGrage = "全部年级";
    } else {
      rec.findGrage = rec.gradeList.find(
        (item) => item.unitName === value
      )?.unitId;
    }
  }

  emit(
    "timeChange",
    convertTime({
      year: rec.yearValue,
      month: rec.monthValue,
      grade: rec.findGrage,
    })
  );

  rec.showGradePicker = false;
  rec.showYearPicker = false;
  rec.showMonthPicker = false;
  rec.showSemesterPicker = false;
};

// 根据学年筛选学期
const filterSemester = (yearValue) => {
  return new Promise<string>((resolve) => {
    let currentSemester = "";

    const semesterList = (rec.monthColumns = rec.yearSemAddVacationList.filter(
      (item) => item.accYearName === yearValue
    )?.[0]?.semAddVacation);

    rec.monthColumns = semesterList.map((item2) => item2.name.slice(9));

    semesterList.forEach((item) => {
      const now = new Date().getTime();
      const begin = new Date(item.beginDay).getTime();
      const end = new Date(item.endDay).getTime();
      if (begin <= now && now <= end) {
        currentSemester = item.name;
      }
    });

    resolve(currentSemester);
  });
};

// 根据学年获取周期列表
const getWeekList = () => {
  return new Promise<string>((resolve) => {
    const time = rec.yearSemAddVacationList.find(
      (item) => item.accYearName === rec.yearValue
    );
    // 根据时间获取当前学期为学年下哪一个学期
    const nowSem = time.semAddVacation.find(
      (item) =>
        new Date(item.beginDay).getTime() <= new Date().getTime() &&
        new Date(item.endDay).getTime() >= new Date().getTime()
    );

    getWeek({
      beginDay: nowSem.beginDay,
      endDay: nowSem.endDay,
    }).then((res) => {
      if (res.code === 0) {
        rec.weekList = res.rows;
        // rec.weekValue = res.rows[0].weekIndex;
        console.log(nowSem, "time");
        // rec.monthColumns = res.rows.map((item) => `第${item.weekIndex}教学周`);
        rec.semesterColumns = time.semAddVacation.map((item) => item.name.slice(9));
        let currentSemester = "";
        currentSemester = nowSem.name.slice(9);

        res.rows.forEach((item) => {
          const now = new Date().getTime();
          const begin = new Date(item.beginDay).getTime();
          const end = new Date(item.endDay).getTime();
          if (begin <= now && now <= end) {
            rec.weekValue = item.weekIndex;
            // 获取当前周元素位置让滚动条滚到当前周
            const index = res.rows.findIndex((item2) => item2.weekIndex === item.weekIndex);
            if (index > 3) {
              setTimeout(() => {
                scrollContainer.value.scrollLeft = 100 * (index - 2);
              }, 0);
            }
          }
        });

        resolve(currentSemester);
      }
    });
  });
};

// 转换时间
const convertTime = (selectTime) => {
  // 待处理的起始和结束时间
  let time = "";

  // 处理后的起始和结束时间
  let startTime = "";
  let endTime = "";

  let grade = [];

  if (rec.baseConfig === "Month") {
    // 判断年份，如果月份大于9就选取前面的年份
    if (selectTime.month.slice(0, -1) >= 9) {
      time = selectTime.year.slice(0, 4) + "/" + selectTime.month.slice(0, -1);
    } else {
      time = selectTime.year.slice(5, 9) + "/" + selectTime.month.slice(0, -1);
    }

    startTime = dayjs(time).startOf("month").format("YYYY-MM-DD HH:mm:ss");
    endTime = dayjs(time)
      .endOf("month")
      .set("hour", 23)
      .set("minute", 59)
      .set("second", 59)
      .format("YYYY-MM-DD HH:mm:ss");
  } else if (rec.baseConfig === "Week") {
    const week = rec.weekList.find((item) => item.weekIndex === rec.weekValue);
    startTime = dayjs(week.beginDay).format("YYYY-MM-DD HH:mm:ss");
    endTime = dayjs(week.endDay)
      .set("hour", 23)
      .set("minute", 59)
      .set("second", 59)
      .format("YYYY-MM-DD HH:mm:ss");
  } else if (rec.baseConfig === "Semester") {
    // 获取当前时间段所在学期
    const semester = rec.yearSemAddVacationList
      .filter(
        (item: any) =>
          new Date(item.beginDay).getTime() <= new Date().getTime() &&
          new Date(item.endDay).getTime() >= new Date().getTime()
      )?.[0]
      ?.semAddVacation.find((item2) => item2.name.slice(9) === selectTime.month);

    rec.yearSemAddVacationList.forEach((item) => {
      item;
    });

    startTime = dayjs(semester.beginDay).format("YYYY-MM-DD HH:mm:ss");
    endTime = dayjs(semester.endDay)
      .set("hour", 23)
      .set("minute", 59)
      .set("second", 59)
      .format("YYYY-MM-DD HH:mm:ss");
  }

  // 处理全部年级
  if (selectTime.grade === "全部年级") {
    grade = rec.gradeList.map((item) => item);
  } else {
    grade = rec.gradeList.filter(
      (item: any) => item.unitId === selectTime.grade
    );
  }

  return {
    startTime,
    endTime,
    grade,
  };
};

const emit = defineEmits(["timeChange"]);
</script>

<style lang="less" scoped>
.ylc-weekList {
  width: 100%;
  height: 48px;
  overflow-x: auto;
  display: flex;
  align-items: center;

  .ylc-weekList-item {
    white-space: nowrap;
    padding: 5px 16px;
    border-radius: 100px;
    background: #f3f5f9;
    color: #616366;
    margin-right: 8px;
  }
}

.action {
  border: 1px solid #3e77fa;
  color: #3E77FA !important;
  background: #fff;
}

.ylc-weekList::-webkit-scrollbar {
  display: none;
}

.select-group {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 48px;
  width: 100%;
  padding: 0 20px;
  background-color: #fff;
  font-size: 14px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 10000;

  .select-year,
  .select-month {
    width: 167.5px;
    display: flex;
    justify-content: center;
    align-items: center;
    white-space: pre;
    flex: 1;
  }

  .bottom-icon {
    margin-left: 3px;
    font-size: 8px;
    transform: translateY(2px);
  }

  /deep/ .van-picker {
    height: 250px;
    position: fixed;
    width: 100%;
    top: 48px;
    left: 0;

    .van-picker__columns {
      height: 250px !important;

      .van-picker-column__wrapper {
        .van-picker-column__item {
          justify-content: center;
          padding-left: 16px;
        }

        .van-picker-column__item--selected {
          color: #3e77fa;
        }
      }
    }
  }
}
</style>
